import React, { useState, useRef, useEffect } from "react";
import "./ImageMagnifier.css";

const ImageMagnifier = ({ src, alt = "图片", width = 400, height = 300, magnifierSize = 150, zoomLevel = 2.5 }) => {
  const [isHovering, setIsHovering] = useState(false);
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
  const imageRef = useRef(null);
  const magnifierRef = useRef(null);

  const handleMouseMove = (e) => {
    if (!imageRef.current) return;

    const rect = imageRef.current.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;

    // 确保鼠标位置在图片范围内
    if (x >= 0 && x <= rect.width && y >= 0 && y <= rect.height) {
      setMousePosition({ x, y });
    }
  };

  const handleMouseEnter = () => {
    setIsHovering(true);
  };

  const handleMouseLeave = () => {
    setIsHovering(false);
  };

  // 计算放大镜的位置
  const magnifierStyle = {
    position: "absolute",
    width: `${magnifierSize}px`,
    height: `${magnifierSize}px`,
    border: "2px solid #333",
    borderRadius: "50%",
    pointerEvents: "none",
    backgroundImage: `url(${src})`,
    backgroundSize: `${width * zoomLevel}px ${height * zoomLevel}px`,
    backgroundPosition: `-${mousePosition.x * zoomLevel - magnifierSize / 2}px -${mousePosition.y * zoomLevel - magnifierSize / 2}px`,
    display: isHovering ? "block" : "none",
    left: `${mousePosition.x - magnifierSize / 2}px`,
    top: `${mousePosition.y - magnifierSize / 2}px`,
    zIndex: 1000,
  };

  return (
    <div className="image-magnifier-container">
      <div
        className="image-container"
        style={{
          position: "relative",
          width: `${width}px`,
          height: `${height}px`,
          overflow: "hidden",
        }}
        onMouseMove={handleMouseMove}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      >
        <img
          ref={imageRef}
          src={src}
          alt={alt}
          style={{
            width: "100%",
            height: "100%",
            objectFit: "cover",
            cursor: "crosshair",
          }}
        />
        <div ref={magnifierRef} style={magnifierStyle} />
      </div>
    </div>
  );
};

export default ImageMagnifier;
